package com.net.xpay.admin.controller.admin;

import com.net.common.model.ResultPagedList;
import com.net.common.util.LocalDateUtil;
import com.net.common.util.SerializationUtil;
import com.net.xpay.admin.vo.UserDailyStatVo;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.partner.PartnerManager;
import com.net.xpay.common.manager.stat.UserDailyStatManager;
import com.net.xpay.common.model.AggMonthUserDailyStatModel;
import com.net.xpay.common.model.AggUserDailyStatModel;
import com.net.xpay.common.model.MonthUserDailyStatModel;
import com.net.xpay.core.model.UserDailyStatSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admin/user-daily-stat")
@Api(tags = "运营/后台用户经营数据统计", description = "运营 后台用户经营数据统计 net")
public class AdminUserDailyStatController {

    @Autowired
    private UserDailyStatManager userDailyStatManager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private PartnerManager partnerManager;

    @ApiOperation("搜索商户数据")
    @PostMapping("/search")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'user-daily-stat::search')")
    public ResultPagedList<UserDailyStatVo> aggSearch(@RequestBody UserDailyStatSearchModel searchModel) {
        //总
        if (searchModel.getDataType() == 0) {
            searchModel.setStartDay(null);
            searchModel.setEndDay(LocalDate.now().minusDays(1L));
        }
        if (searchModel.getDataType() == 1) {
            searchModel.setDay(LocalDate.now().minusDays(1L));
        }
        if (searchModel.getDataType() == 2) {
            searchModel.setStartDay(LocalDateUtil.getMonthStartDay(LocalDate.now()));
            searchModel.setEndDay(LocalDate.now().minusDays(1L));
        }

        if (searchModel.getType() == 0) {
            searchModel.setColumn("total_success_count");
            searchModel.setOrderby("desc");
        }
        if (searchModel.getType() == 1) {
            searchModel.setColumn("total_success_trans_amount");
            searchModel.setOrderby("desc");
        }
        if (searchModel.getType() == 2) {
            searchModel.setColumn("total_fail_count");
            searchModel.setOrderby("desc");
        }
        //昨日未活跃
        if (searchModel.getType() == 3 && searchModel.getDataType() == 1) {
            LocalDate yesterday = LocalDate.now().minusDays(1L);
            LocalDate dayBefore = LocalDate.now().minusDays(2L);

            List<AggUserDailyStatModel> records = userDailyStatManager.daySearch(yesterday, dayBefore);

            List<UserDailyStatVo> vos = BeanCopierUtil.batchCopy(AggUserDailyStatModel.class, UserDailyStatVo.class, records);
            for (UserDailyStatVo vo : vos) {
                User user = userManager.getById(vo.getUserId());
                vo.setName(user.getName());
                if (user.getPartnerId() != null){
                    Partner partner = partnerManager.getById(user.getPartnerId());
                    vo.setPartnerName(partner.getName());
                }
            }
            return new ResultPagedList<>(vos, (long) records.size(), searchModel);
        }
        //月未活跃
        if (searchModel.getType() == 3 && searchModel.getDataType() == 2) {
            //当前年月
            Integer nowYear = LocalDate.now().getYear();
            Integer nowMonth = LocalDate.now().getMonthValue();
            //上个月
            LocalDate date = LocalDate.now().minusMonths(1);
            Integer yestYear = date.getYear();
            Integer yestMonth = date.getMonthValue();
            //上个月的统计数据
            List<AggMonthUserDailyStatModel> yearList = userDailyStatManager.listByData(yestYear, yestMonth);

            List<MonthUserDailyStatModel> list = new ArrayList<>();
            for (AggMonthUserDailyStatModel aggUserDailyStatModel : yearList) {
                //这个用户这个月的转账金额
                AggMonthUserDailyStatModel model = userDailyStatManager.sumByUserIdAndData(aggUserDailyStatModel.getUserId(), nowYear, nowMonth);
                MonthUserDailyStatModel statModel = new MonthUserDailyStatModel();
                BigDecimal increase = model.getTotalSuccessTransAmount().subtract(aggUserDailyStatModel.getTotalSuccessTransAmount());

                if (increase.compareTo(new BigDecimal("0")) < 0) {
                    statModel.setUserId(aggUserDailyStatModel.getUserId());
                    statModel.setIncrease(increase);
                    statModel.setYestAmount(aggUserDailyStatModel.getTotalSuccessTransAmount());
                    list.add(statModel);
                }

            }

            list.sort(Comparator.comparing(MonthUserDailyStatModel::getIncrease));

            List<UserDailyStatVo> vos = BeanCopierUtil.batchCopy(MonthUserDailyStatModel.class, UserDailyStatVo.class, list);
            log.info("aggSearch vos={}", SerializationUtil.obj2String(vos));
            for (UserDailyStatVo vo : vos) {
                User user = userManager.getById(vo.getUserId());
                vo.setName(user.getName());
                if (user.getPartnerId() != null){
                    Partner partner = partnerManager.getById(user.getPartnerId());
                    vo.setPartnerName(partner.getName());
                }
            }
            return new ResultPagedList<>(vos, (long) list.size(), searchModel);
        }


        List<AggUserDailyStatModel> records = userDailyStatManager.aggSearch(searchModel);
        long count = userDailyStatManager.aggSearchCount(searchModel);
        List<UserDailyStatVo> vos = BeanCopierUtil.batchCopy(AggUserDailyStatModel.class, UserDailyStatVo.class, records);

        for (UserDailyStatVo vo : vos) {
            String failRate = null;
            if (vo.getTotalCount() != 0L) {
                failRate = new BigDecimal(vo.getTotalFailCount()).multiply(new BigDecimal("100")).divide(new BigDecimal(vo.getTotalCount()), 2, RoundingMode.HALF_UP).toString();
            }
            vo.setFailRate(failRate);

            User user = userManager.getById(vo.getUserId());
            vo.setName(user.getName());
            if (user.getPartnerId() != null){
                Partner partner = partnerManager.getById(user.getPartnerId());
                vo.setPartnerName(partner.getName());
            }
        }
        return new ResultPagedList<>(vos, count, searchModel);
    }


}
